﻿using Common.Log;
using eloamComLib;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Timers;
using System.Windows;
using System.Windows.Controls;

namespace EloamCom
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private EloamGlobal global;
        private EloamVideo m_pVideo;
        private int m_timerValue;
        private EloamVideoCap m_pVideoCap;

        private EloamImage m_globalTempImage;

        public EloamMemory m_pTemplate;
        public EloamMemory m_pFeature;

        bool hasClickOcrList = false;
        //定义系统计时器
        private System.Timers.Timer timer;

        private System.Windows.Forms.Timer timerWin;

        //设备列表
        private List<EloamDevice> m_deviceList;

        ServiceOrcl.Scanner client = new ServiceOrcl.Scanner();
        private string userid = ConfigurationManager.AppSettings["Userid"];
        private string ftpUrl = ConfigurationManager.AppSettings["ftpUrl"];
        private string userName = ConfigurationManager.AppSettings["userName"];
        private string passWord = ConfigurationManager.AppSettings["passWord"];
        private string type = ConfigurationManager.AppSettings["UploadType"] ?? "1";
        private string ftpDirctory = ConfigurationManager.AppSettings["ftpDirctory"];
        public MainWindow()
        {
            InitializeComponent();
            global = new EloamGlobal();
            m_deviceList = new List<EloamDevice>();

            m_pFeature = null;
            m_pTemplate = null;
            m_pVideoCap = null;

            FormInit();

            Init();
            Thread th = new Thread(arrObj =>
            {
                try
                {
                    BindComboBox();
                    BindListBox(arrObj);
                }
                catch (Exception ex)
                {
                    LogManage.addLogErr("MainWindow", ex.Message);
                    MessageBox.Show("程序异常=>" + ex.Message, "提示", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            });
            th.IsBackground = true;
            th.Start(new object[] { txtName.Text.Trim(), txtCardId.Text.Trim() });
        }

        public void FormInit()
        {
            //传入设备状态改变事件
            global.DevChange += DevChangeEventHandler;
            //传入移动监测事件
            global.MoveDetec += MoveDetecEventHandler;
            //视频播放事件
            global.Arrival += ArrivalEventHandler;
            //二代证
            global.IdCard += IdCardEventHandler;
            //Ocr识别事件
            global.Ocr += OcrEventHandler;

            //初始化设备
            global.InitDevs();

            if (!global.InitIdCard())
            {
                button_StartIdCardRead.IsEnabled = false;
                button_StopReadIDCard.IsEnabled = false;
            }

            if (global.InitBarcode())
            {
                barcode.IsEnabled = true;
            }
            else
            {
                barcode.IsEnabled = false;
            }

            //if (global.InitOcr())
            //{
            //    ocr.IsEnabled = true;
            //    ocrList.IsEnabled = true;
            //}

            if (global.VideoCapInit())
            {
                startRecord.IsEnabled = true;
                stopRecord.IsEnabled = true;
            }
            else
            {
                startRecord.IsEnabled = false;
                stopRecord.IsEnabled = false;
            }
        }

        public void Init()
        {
            selectDevice.IsEnabled = true;
            selectResolution.IsEnabled = true;
            selectMode.IsEnabled = true;

            openVideo.IsEnabled = true;
            closeVideo.IsEnabled = false;
            turnLeft.IsEnabled = false;
            turnRight.IsEnabled = false;
            exchangeLeftRight.IsEnabled = false;
            exchangeUpDown.IsEnabled = false;
            openProperty.IsEnabled = false;

            rectify.IsEnabled = false;
            rectify.IsChecked = false;
            removeGround.IsEnabled = false;
            removeGround.IsChecked = false;
            autoShoot.IsEnabled = false;
            autoShoot.IsChecked = false;

            openTimer.IsEnabled = false;
            openTimer.IsChecked = false;
            edit_Timer.IsEnabled = false;

            compoundShoot.IsEnabled = false;
            compoundShoot.IsChecked = false;

            pictureSavePath.IsEnabled = false;
            shoot.IsEnabled = false;
            impdata.IsEnabled = false;

            m_timerValue = 5;
            edit_Timer.Text = m_timerValue.ToString();
            pictureSavePath.Text = "D:/PZ/";

            barcode.IsEnabled = false;
        }

        private void BindComboBox()
        {
            IList<Info> infoList = new List<Info>();
            var value = "请选择证件类型";
            infoList.Add(new Info() { Id = value, Name = value });
            var arrLb = client.GetLb();
            arrLb.ToList().ForEach(t =>
            {
                infoList.Add(new Info() { Id = t, Name = t });
            });
            this.Dispatcher.Invoke(new Action<IEnumerable<Info>>(BindCombobox), infoList);
        }

        private void BindCombobox(IEnumerable list)
        {
            comboBox1.ItemsSource = list;
            comboBox1.SelectedIndex = 4;
        }


        //设备状态改变事件响应
        public void DevChangeEventHandler(int type, int idx, int dbt)
        {
            if (1 == type)
            {
                if (1 == dbt)//设备到达
                {
                    EloamDevice tempDevice = (EloamDevice)global.CreateDevice(1, idx);
                    m_deviceList.Add(tempDevice);

                    selectDevice.Items.Add(tempDevice.GetFriendlyName());
                    if (-1 == selectDevice.SelectedIndex)
                    {
                        selectDevice.SelectedIndex = 0;//改变所选设备
                    }

                }
                else if (2 == dbt)//设备丢失
                {
                    EloamDevice tempDevice = m_deviceList[idx];
                    if (null != m_pVideo)
                    {
                        EloamDevice tempDevice2 = (EloamDevice)m_pVideo.GetDevice();
                        if (tempDevice == tempDevice2)
                        {
                            closeVideo_Click(new object(), new EventArgs());
                        }
                    }

                    m_deviceList[idx].Destroy();
                    m_deviceList.RemoveAt(idx);
                    selectDevice.Items.RemoveAt(idx);
                    if (-1 == selectDevice.SelectedIndex)
                    {
                        if (0 != m_deviceList.Count)
                        {
                            selectDevice.SelectedIndex = 0;
                        }
                        else
                        {
                            selectDevice.Items.Clear();
                            selectMode.Items.Clear();
                            selectResolution.Items.Clear();
                        }
                    }
                }
            }
        }

        private void closeVideo_Click(object sender, EventArgs e)
        {
            if (null != m_pVideo)
            {
                eloamView.SetText(null, 0);
                m_pVideo.Destroy();
                m_pVideo = null;
            }

            eloamView.SetText(null, 0);

            Reset();
        }

        public void Reset()
        {
            Init();
        }

        private void openVideo_Click(object sender, RoutedEventArgs e)
        {
            int devIdx = selectDevice.SelectedIndex;
            if (selectMode.SelectedItem == null) return;
            string curModeString = selectMode.SelectedItem.ToString();
            int modeIdx = (curModeString == "YUY2" ? 1 :
                            (curModeString == "MJPG" ? 2 :
                                (curModeString == "UYVY" ? 4 :
                                    -1)));
            int resIdx = selectResolution.SelectedIndex;

            if (-1 != devIdx)
            {
                if (null != m_pVideo)
                {
                    m_pVideo.Destroy();
                    m_pVideo = null;
                }

                EloamDevice tempDevice = m_deviceList[devIdx];
                m_pVideo = (EloamVideo)tempDevice.CreateVideo(resIdx, modeIdx);

                if (null != m_pVideo)
                {
                    eloamView.SelectVideo(m_pVideo);
                    eloamView.SetText("打开视频中，请等待...", RGB(255, 255, 255));

                    selectDevice.IsEnabled = false;
                    selectResolution.IsEnabled = false;
                    selectMode.IsEnabled = false;

                    openVideo.IsEnabled = false;
                    closeVideo.IsEnabled = true;
                }
            }
        }

        public uint RGB(uint r, uint g, uint b)
        {
            return (((b << 16) | (g << 8)) | r);
        }

        private void selectDevice_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            int idx = selectDevice.SelectedIndex;//记录当前所选设备

            selectMode.Items.Clear();

            if (-1 != idx)
            {
                EloamDevice tempDevice = m_deviceList[idx];

                //加载模式列表
                int subtype = tempDevice.GetSubtype();
                if (0 != (subtype & 1))
                {
                    selectMode.Items.Add("YUY2");
                }
                if (0 != (subtype & 2))
                {
                    selectMode.Items.Add("MJPG");
                }
                if (0 != (subtype & 4))
                {
                    selectMode.Items.Add("UYVY");
                }

                //若为辅摄像头，优先选择MJPG方式
                if (1 != tempDevice.GetEloamType() && (0 != (subtype & 2)) && (0 != (subtype & 1)))
                {
                    selectMode.SelectedIndex = 1;
                }
                else
                {
                    selectMode.SelectedIndex = 0;
                }

                openVideo.IsEnabled = true;
            }
            else
            {
                openVideo.IsEnabled = false;
            }
        }

        private void selectMode_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            int idx = selectDevice.SelectedIndex;//记录当前所选设备

            selectResolution.Items.Clear();

            if (-1 != idx)
            {
                EloamDevice tempDevice = m_deviceList[idx];
                //加载分辨率列表
                int subtype = -1;
                string curModeString = selectMode.SelectedItem.ToString();
                subtype = (curModeString == "YUY2" ? 1 :
                            (curModeString == "MJPG" ? 2 :
                                (curModeString == "UYVY" ? 4 :
                                    -1)));
                if (-1 != subtype)
                {
                    int count = tempDevice.GetResolutionCountEx(subtype);
                    for (int i = 0; i < count; ++i)
                    {
                        int width = tempDevice.GetResolutionWidthEx(subtype, i);
                        int height = tempDevice.GetResolutionHeightEx(subtype, i);

                        string str = width.ToString() + "*" + height.ToString();
                        selectResolution.Items.Add(str);
                    }
                    selectResolution.SelectedIndex = 0;
                }
            }
        }

        private void turnLeft_Click(object sender, RoutedEventArgs e)
        {
            m_pVideo.RotateLeft();
        }

        private void turnRight_Click(object sender, RoutedEventArgs e)
        {
            m_pVideo.RotateRight();
        }

        private void exchangeLeftRight_Click(object sender, RoutedEventArgs e)
        {
            m_pVideo.Mirror();
        }

        private void exchangeUpDown_Click(object sender, RoutedEventArgs e)
        {
            m_pVideo.Flip();
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            closeVideo_Click(new object(), new EventArgs());

            int count = m_deviceList.Count;
            if (count != 0)
            {
                for (int i = 0; i < count; i++)
                {
                    m_deviceList[i].Destroy();
                }
            }
            m_deviceList.Clear();

            global.DeinitBarcode();

            if (null != m_pTemplate)
            {
                m_pTemplate.Destroy();
                m_pTemplate = null;
            }
            if (null != m_pFeature)
            {
                m_pFeature.Destroy();
                m_pFeature = null;
            }

            if (m_pVideoCap != null)
            {
                m_pVideoCap.VideoCapStop();
                m_pVideoCap.Destroy();
                m_pVideoCap = null;
            }

            global.DeinitBiokey();
            global.DeinitIdCard();
            global.DeinitDevs();
            global.DeinitOcr();

            //传出设备状态改变事件
            global.DevChange -= DevChangeEventHandler;
            //传出移动监测事件
            global.MoveDetec -= MoveDetecEventHandler;
            //传出视频播放事件
            global.Arrival -= ArrivalEventHandler;
            //传出二代证
            global.IdCard -= IdCardEventHandler;
            //传出Ocr识别事件
            global.Ocr -= OcrEventHandler;
            System.Environment.Exit(0);
        }

        //二代证事件响应
        public void IdCardEventHandler(int ret)
        {
            // Fire_MoveDetec
            StringBuilder MyStringBuilder = new StringBuilder();

            for (int i = 0; i < 16; i++)
            {
                string read;
                read = global.GetIdCardData(i + 1);
                MyStringBuilder.Append(read);
                MyStringBuilder.Append("\r\n");
            }
            string show = MyStringBuilder.ToString();
            EloamImage img = (EloamImage)global.GetIdCardImage(1);
            img.Save("idcard.jpg", 0);
            img.Destroy();
            MessageBox.Show(show);
        }

        //移动监测事件响应
        public void MoveDetecEventHandler(object pVideo, int id)
        {
            // Fire_MoveDetec
            shoot_Click(new object(), new RoutedEventArgs());
        }

        //视频播放事件
        private void ArrivalEventHandler(object pVideo, int id)
        {
            if (0 == id)//视频第一帧
            {
                openVideo.IsEnabled = false;
                closeVideo.IsEnabled = true;
                turnLeft.IsEnabled = true;
                turnRight.IsEnabled = true;
                exchangeLeftRight.IsEnabled = true;
                exchangeUpDown.IsEnabled = true;
                openProperty.IsEnabled = true;

                rectify.IsEnabled = true;
                //rectify.IsChecked = true;
                removeGround.IsEnabled = true;
                autoShoot.IsEnabled = true;

                openTimer.IsEnabled = true;
                edit_Timer.IsEnabled = true;

                compoundShoot.IsEnabled = true;

                pictureSavePath.IsEnabled = true;
                shoot.IsEnabled = true;
                impdata.IsEnabled = true;

                barcode.IsEnabled = true;
            }
        }

        //Ocr识别事件
        private void OcrEventHandler(int flag, int ret)
        {
            if (hasClickOcrList)//只在识别列表时生效
            {
                if (1 == flag)
                {
                    if (0 == ret)
                    {
                        global.SaveOcr("D://ocrList.pdf", 0);
                        MessageBox.Show("识别成功！");
                    }
                    if (-1 == ret)
                    {
                        MessageBox.Show("识别失败！");
                    }
                    hasClickOcrList = false;
                }
                if (2 == flag)
                {
                    OcrPercentage.Text = ret.ToString() + "%";
                }
            }
        }

        private void shoot_Click(object sender, RoutedEventArgs e)
        {

        }

        private void openProperty_Click(object sender, RoutedEventArgs e)
        {
            if (null != m_pVideo)
            {
                EloamDevice tempDevice = (EloamDevice)m_pVideo.GetDevice();
                tempDevice.ShowProperty(eloamView.GetView());
            }
        }

        void timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            //impdata_Click(sender, null);//e
            test(sender, e);
        }

        private void test(object sender, ElapsedEventArgs e)
        {
            var val = comboBox1.Text;
        }

        private void impdata_Click(object sender, RoutedEventArgs e)
        {
            Thread th = new Thread(arrObj =>
            {
                try
                {
                    var obj = arrObj as object[];
                    var cardType = obj[0].ToString();
                    var selectItem = obj[1];
                    var savePath = obj[2].ToString();
                    var compoundShootIsCheck = (bool)obj[3];
                    var barcodeIsCheck = (bool)obj[4];
                    if (string.IsNullOrWhiteSpace(cardType) || cardType == "请选择证件类型")
                    {
                        MessageBox.Show("请选择证件类型", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                        return;
                    }
                    if (null == m_pVideo)
                    {
                        return;
                    }
                    if (selectItem == null)
                    {
                        MessageBox.Show("请选择一项", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                        return;
                    }
                    impdata.Dispatcher.BeginInvoke(new Action(() => { impdata.IsEnabled = false; impdata.Content = "正在拍照.."; }));
                    EloamView tempView = (EloamView)eloamView.GetView();
                    EloamImage tempImage = (EloamImage)m_pVideo.CreateImage(0, tempView);
                    impdata.Dispatcher.BeginInvoke(new Action(() => { impdata.IsEnabled = false; impdata.Content = "拍摄完成，正在上传.."; }));
                    var model = (FamilyInfo)selectItem;
                    if (null != tempImage)
                    {
                        DateTime dateTime = DateTime.Now;
                        string time = DateTime.Now.ToString(
                            "yyyyMMdd_HHmmss_fff", DateTimeFormatInfo.InvariantInfo);

                        string filename = savePath + "\\" + model.Iid + "\\" + cardType + "\\Manual_" + time + ".jpg";

                        if (compoundShootIsCheck)//合成拍照
                        {
                            if (null == m_globalTempImage)
                            {
                                m_globalTempImage = tempImage;
                                MessageBox.Show("<合成拍摄中...> 请放下一张");
                            }
                            else
                            {
                                int w1 = m_globalTempImage.GetWidth();
                                int w2 = tempImage.GetWidth();
                                int width = (w1 > w2) ? w1 : w2;
                                int h1 = m_globalTempImage.GetHeight();
                                int h2 = tempImage.GetHeight();
                                int height = h1 + h2;

                                EloamImage compoundImage =
                                    (EloamImage)global.CreateImage(width, height, 3);
                                if (null != compoundImage)
                                {
                                    EloamRect rcDest1 = (EloamRect)global.CreateRect(0, 0, w1, h1);
                                    EloamRect rcSrc1 = (EloamRect)global.CreateRect(0, 0, w1, h1);
                                    compoundImage.Blend(rcDest1, m_globalTempImage, rcSrc1, 0, 0);

                                    EloamRect rcDest2 = (EloamRect)global.CreateRect(0, h2, w2, h2);
                                    EloamRect rcSrc2 = (EloamRect)global.CreateRect(0, 0, w2, h2);
                                    compoundImage.Blend(rcDest2, tempImage, rcSrc2, 0, 0);
                                    var directoryPath = System.IO.Path.GetDirectoryName(filename);
                                    if (!Directory.Exists(directoryPath))
                                    {
                                        Directory.CreateDirectory(directoryPath);
                                    }
                                    string strMsg = string.Empty;
                                    if (compoundImage.Save(filename, 0))
                                    {
                                        bool flag = SaveOrcl(model.Iid, cardType, filename, ref strMsg);
                                        if (!flag)
                                        {
                                            var idx = eloamThumbnail.GetCount() - 1;
                                            eloamThumbnail.Remove(idx, true);
                                            MessageBox.Show("保存失败=>" + strMsg);
                                        }
                                    }
                                    else
                                    {
                                        MessageBox.Show("保存失败，请检查保存路径设置是否正确!");
                                    }
                                }
                                m_globalTempImage.Destroy();
                                m_globalTempImage = null;
                            }
                        }
                        else
                        {
                            var directoryPath = System.IO.Path.GetDirectoryName(filename);
                            if (!Directory.Exists(directoryPath))
                            {
                                Directory.CreateDirectory(directoryPath);
                            }
                            if (tempImage.Save(filename, 0))
                            {
                                string msg = string.Empty;
                                bool flag = SaveOrcl(model.Iid, cardType, filename, ref msg);
                                if (!flag)
                                {
                                    var idx = eloamThumbnail.GetCount() - 1;
                                    eloamThumbnail.Remove(idx, true);//删除刚才拍摄的图片
                                    MessageBox.Show("保存失败=>" + msg);
                                }
                                if (barcodeIsCheck)
                                {
                                    global.DiscernBarcode(tempImage);
                                    int count = global.GetBarcodeCount();
                                    if (count > 0)
                                    {
                                        string strMsg = "";
                                        for (int i = 0; i < count; ++i)
                                        {
                                            strMsg += global.GetBarcodeData(i) + "\r\n";
                                        }
                                        MessageBox.Show(strMsg);
                                    }
                                    else
                                    {
                                        MessageBox.Show("识别条码失败");
                                    }
                                }
                            }
                            else
                            {
                                MessageBox.Show("保存失败，请检查保存路径设置是否正确!");
                            }
                        }
                        impdata.Dispatcher.BeginInvoke(new Action(() => { impdata.IsEnabled = true; impdata.Content = "拍摄"; }));
                    }
                }
                catch (Exception ex)
                {
                    LogManage.addLogErr("impdata_Click", ex.Message);
                    impdata.Dispatcher.BeginInvoke(new Action(() => { impdata.IsEnabled = true; impdata.Content = "拍摄"; }));
                    MessageBox.Show("程序异常=>" + ex.Message, "提示", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            });
            th.IsBackground = true;
            th.Start(new object[] { comboBox1.Text, DataGrid.SelectedItem, pictureSavePath.Text, compoundShoot.IsChecked, barcode.IsChecked });
        }

        /// <summary>
        /// 将文件转换为byte数组
        /// </summary>
        /// <param name="path">文件地址</param>
        /// <returns>转换后的byte数组</returns>
        public byte[] File2Bytes(string path)
        {
            if (!System.IO.File.Exists(path))
            {
                return new byte[0];
            }
            FileInfo fi = new FileInfo(path);
            byte[] buff = new byte[fi.Length];
            FileStream fs = fi.OpenRead();
            fs.Read(buff, 0, Convert.ToInt32(fs.Length));
            fs.Close();
            return buff;
        }

        /// <summary>
        /// 将byte数组转换为文件并保存到指定地址
        /// </summary>
        /// <param name="buff">byte数组</param>
        /// <param name="savepath">保存地址</param>
        public void Bytes2File(byte[] buff, string savepath)
        {
            if (System.IO.File.Exists(savepath))
            {
                return;
            }
            var directoryName = System.IO.Path.GetDirectoryName(savepath);
            if (!Directory.Exists(directoryName))
            {
                Directory.CreateDirectory(directoryName);
            }
            using (FileStream fs = new FileStream(savepath, FileMode.CreateNew))
            {
                using (BinaryWriter bw = new BinaryWriter(fs))
                {
                    bw.Write(buff, 0, buff.Length);
                }
            }
        }

        private bool SaveOrcl(string iid, string lb, string filename, ref string strMsg)
        {
            try
            {
                var byteData = File2Bytes(filename);
                var fileName = System.IO.Path.GetFileName(filename);
                eloamView.PlayCaptureEffect();
                eloamThumbnail.Add(filename);
                if (type == "1")
                {
                    client.UploadEloam(byteData, iid, userid, lb, fileName);
                }
                else
                {
                    strMsg = client.UploadFileToFtp(ftpUrl, userName, passWord, byteData, fileName, iid, userid, lb, ftpDirctory);
                    if (!string.IsNullOrWhiteSpace(strMsg))
                    {
                        LogManage.addLogErr("SaveOrcl", strMsg);
                        //MessageBox.Show("上传失败=>" + strMsg);
                        return false;
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                strMsg = ex.Message;
                LogManage.addLogErr("SaveOrcl", ex.Message);
                //MessageBox.Show("入库出错=>" + ex.Message);
                return false;
            }
        }


        private void delete_Click(object sender, RoutedEventArgs e)
        {
            var list = new List<int>();
            for (int i = 0; i < eloamThumbnail.GetCount(); i++)
            {
                var isChecked = eloamThumbnail.GetCheck(i);
                if (isChecked) list.Add(i);
            }
            if (list.Count == 0)
            {
                MessageBox.Show("请勾选要删除的图片", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }
            var dr = MessageBox.Show("确定要删除吗?", "提示", MessageBoxButton.OKCancel, MessageBoxImage.Information);
            if (dr != MessageBoxResult.OK) return;
            for (int i = eloamThumbnail.GetCount() - 1; i >= 0; i--)
            {
                var isChecked = eloamThumbnail.GetCheck(i);
                if (isChecked)
                {
                    var fileFullName = eloamThumbnail.GetFileName(i);
                    var arrValue = fileFullName.Split('\\');
                    if (arrValue.Length >= 4)
                    {
                        var name = arrValue[arrValue.Length - 1];
                        var lb = arrValue[arrValue.Length - 2];
                        var iid = arrValue[arrValue.Length - 3];
                        if (type == "1")
                        {
                            if (client.DeleteImage(iid, name, lb))
                            {
                                eloamThumbnail.Remove(i, true);
                            }
                        }
                        else
                        {
                            var path = string.IsNullOrWhiteSpace(ftpDirctory) ? string.Concat("/", iid, "/", lb, "/") : string.Concat("/", ftpDirctory, "/", iid, "/", lb, "/");
                            var isSuccess = client.DeleteFtpFile(ftpUrl, userName, passWord, path, name);
                            eloamThumbnail.Remove(i, true);
                        }
                    }
                }
            }
        }

        private void BindListBox(object arrObj)
        {
            var obj = (object[])arrObj;
            var name = obj[0].ToString();
            var cardId = obj[1].ToString();
            var dataSet = client.GetSQInfoData(name, cardId);
            if (dataSet.Tables != null)
            {
                var dtTemp = dataSet.Tables[0];
                var list = dtTemp.Rows.Cast<DataRow>().Select(t => new FamilyInfo
                {
                    Iid = t["iid"].ToString(),
                    Name = t.Field<string>("FAMILY_NAME"),
                    CardId = t.Field<string>("FAMILY_ZJHM"),
                    Fwjzmj = t.Field<string>("FWJZMJ"),
                    Status = t.Field<string>("ZT")
                });
                this.Dispatcher.Invoke(new Action<IEnumerable<FamilyInfo>>(BindData), list);
            }
        }

        private void BindData(IEnumerable<FamilyInfo> list)
        {
            DataGrid.ItemsSource = list;
            DataGrid.GridLinesVisibility = DataGridGridLinesVisibility.Horizontal;
            DataGrid.SelectedIndex = 0;
            lblLoadMsg.Visibility = System.Windows.Visibility.Collapsed;
        }

        private void btnQuery_Click(object sender, RoutedEventArgs e)
        {
            Thread th = new Thread(arrObj =>
            {
                try
                {
                    BindListBox(arrObj);
                }
                catch (Exception ex)
                {
                    LogManage.addLogErr("btnQuery_Click", ex.Message);
                    MessageBox.Show("程序异常=>" + ex.Message, "提示", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            });
            th.IsBackground = true;
            th.Start(new object[] { txtName.Text.Trim(), txtCardId.Text.Trim() });
        }

        private void DataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            Thread th = new Thread(arrObj =>
            {
                try
                {
                    LoadImageInfo(arrObj);
                }
                catch (Exception ex)
                {
                    LogManage.addLogErr("DataGrid_SelectionChanged", ex.Message);
                    MessageBox.Show("程序异常=>" + ex.Message, "提示", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            });
            th.IsBackground = true;
            th.Start(new object[] { DataGrid.SelectedItem, pictureSavePath.Text.Trim() });
        }

        private void LoadImageInfo(object arrObj)
        {
            var obj = (object[])arrObj;
            var selectItem = obj[0];
            var savePath = obj[1].ToString();

            if (selectItem == null) return;
            if (string.IsNullOrWhiteSpace(savePath))
            {
                MessageBox.Show("拍照路径不能为空", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }
            chkAll.Dispatcher.BeginInvoke(new Action(() => { chkAll.IsChecked = false; }));
            eloamThumbnail.Clear(false);
            var model = (FamilyInfo)selectItem;
            var iid = model.Iid;
            ServiceOrcl.Scanner client = new ServiceOrcl.Scanner();
            var directoryName = System.IO.Path.Combine(savePath, iid);
            if (type == "1")
            {
                var list = client.GetEloamImg(iid);
                list.ToList().ForEach(t =>
                {
                    byte[] buffer = Convert.FromBase64String(t[0]);
                    string lb = t[1];
                    string name = t[2];
                    var fileName = System.IO.Path.Combine(directoryName, lb, name);
                    Bytes2File(buffer, fileName);
                    eloamThumbnail.Add(fileName);
                });
            }
            else
            {
                var filePath = System.IO.Path.Combine(savePath, iid);
                client.DownloadFileForDirectory(ftpUrl, userName, passWord, iid, directoryName, ftpDirctory);
                if (!Directory.Exists(filePath)) return;
                var arrDir = Directory.GetDirectories(filePath);
                arrDir.ToList().ForEach(t =>
                {
                    string[] filenames = Directory.GetFiles(t);
                    filenames.ToList().ForEach(f =>
                    {
                        if (File.Exists(f))
                        {
                            eloamThumbnail.Add(f);
                        }
                    });
                });
            }
        }

        private void rectify_Click(object sender, RoutedEventArgs e)
        {
            if (null != m_pVideo)
            {
                if ((bool)rectify.IsChecked)
                {
                    m_pVideo.EnableDeskew(0);
                }
                else
                {
                    m_pVideo.DisableDeskew();
                }
            }
        }

        private void rectify_Checked(object sender, RoutedEventArgs e)
        {
            rectify_Click(sender, e);
        }

        private void removeGround_Click(object sender, RoutedEventArgs e)
        {
            if (null != m_pVideo)
            {
                if ((bool)removeGround.IsChecked)
                {
                    m_pVideo.EnableDelBkColor(0);
                }
                else
                {
                    m_pVideo.DisableDelBkColor();
                }
            }
        }

        private void autoShoot_Click(object sender, RoutedEventArgs e)
        {
            if (null != m_pVideo)
            {
                if ((bool)autoShoot.IsChecked)
                {
                    m_pVideo.EnableMoveDetec(0);
                }
                else
                {
                    m_pVideo.DisableMoveDetec();
                }
            }
        }

        private void openTimer_Click(object sender, RoutedEventArgs e)
        {
            if ((bool)openTimer.IsChecked)
            {
                edit_Timer.IsEnabled = false;

                //timer = new System.Timers.Timer();
                //timer.Enabled = true;
                //timer.Interval =
                //    uint.Parse(edit_Timer.Text) * 1000;//单位为毫秒
                //timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);

                timerWin = new System.Windows.Forms.Timer();
                timerWin.Enabled = true;
                timerWin.Interval = int.Parse(edit_Timer.Text) * 1000;//单位为毫秒
                timerWin.Tick += timerWin_Tick;
            }
            else
            {
                //timer.Stop();
                //timer.Enabled = false;
                timerWin.Stop();
                timerWin.Enabled = false;
                edit_Timer.IsEnabled = true;
            }
        }

        void timerWin_Tick(object sender, EventArgs e)
        {
            impdata_Click(sender, new RoutedEventArgs());
        }

        private void compoundShoot_Click(object sender, RoutedEventArgs e)
        {
            if ((bool)compoundShoot.IsChecked)
            {
                if (null != m_globalTempImage)
                {
                    m_globalTempImage.Destroy();
                    m_globalTempImage = null;
                }
            }
        }

        private void ocr_Click(object sender, RoutedEventArgs e)
        {
            Thread th = new Thread(() =>
            {
                if (null == m_pVideo)
                {
                    MessageBox.Show("视频未打开");
                    return;
                }
                EloamView tempView = (EloamView)eloamView.GetView();
                EloamImage tempImage = (EloamImage)m_pVideo.CreateImage(0, tempView);
                if (tempImage != null)
                {
                    global.DiscernOcr(1, tempImage);
                    global.WaitOcrDiscern();//同步等待
                    var fileFullName = "D://ocr.doc";
                    global.SaveOcr(fileFullName, 0);
                    MessageBox.Show("识别完成,保存路径为" + fileFullName);
                }
            });
            th.IsBackground = true;
            th.Start();
        }


        private void ocrList_Click(object sender, RoutedEventArgs e)
        {
            EloamView tempView = (EloamView)eloamView.GetView();
            EloamImage tempImage = (EloamImage)global.CreateImageFromFile("D:\\1.jpg", 0);
            EloamImage tempImage2 = (EloamImage)global.CreateImageFromFile("D:\\2.jpg", 0);
            EloamImageList tempImageList = (EloamImageList)global.CreateImageList();
            if (tempImageList != null && tempImage != null && tempImage2 != null)
            {
                hasClickOcrList = true;

                tempImageList.Add(tempImage);
                tempImageList.Add(tempImage2);
                global.DiscernOcrList(1, tempImageList);//异步
            }
            else
            {
                MessageBox.Show("视频未打开");
            }
        }

        private void startRecord_Click(object sender, RoutedEventArgs e)
        {
            if (null != m_pVideo)
            {
                int videoOutputWidth = m_pVideo.GetWidth();
                int videoOutputHeight = m_pVideo.GetHeight();
                //录像时，打开视频的分辨率越低，帧率越高,一般不超过200w像素
                //所设置的帧率应尽可能高于实际帧率，避免丢帧
                const int FrameRate = 15;//此参数可根据录像分辨率与机型实际帧率调节
                const int CheckWidth = 1600;
                const int CheckHeight = 1200;
                //主流视频分辨率少有大于200万的，因此为节约cpu资源，当分辨率大于200w，应采用200w的配置录制
                if ((videoOutputWidth * videoOutputHeight) > (CheckWidth * CheckHeight))
                {
                    MessageBoxButton msgButton = MessageBoxButton.YesNo;
                    var dr = MessageBox.Show(
                        "视频分辨率小于200万时，录制效果最佳，建议您切换到1600X1200或相近分辨率后继续录制视频",
                        "录像", msgButton);
                    if (dr == MessageBoxResult.Yes)//如果点击“确定”按钮
                    {
                        return;
                    }
                    videoOutputWidth = CheckWidth;
                    videoOutputHeight = CheckHeight;
                }

                if (m_pVideoCap != null)
                {
                    m_pVideoCap.VideoCapStop();
                    m_pVideoCap.Destroy();
                    m_pVideoCap = null;
                }

                m_pVideoCap = (EloamVideoCap)global.CreatVideoCap();
                if (null == m_pVideoCap)
                {
                    MessageBox.Show("创建录像对象失败");
                    return;
                }

                int nSelectMic = -1;
                if (global.VideoCapGetAudioDevNum() > 0)//有麦克风
                {
                    nSelectMic = 0;
                }

                if (!m_pVideoCap.VideoCapPreCap(
                    "D://eloamVideo.mp4",
                    nSelectMic,
                    FrameRate,
                    1,
                    videoOutputWidth,
                    videoOutputHeight))
                {
                    MessageBox.Show("录像预处理失败");
                    return;
                }
                if (!m_pVideoCap.VideoCapAddVideoSrc(m_pVideo))
                {
                    MessageBox.Show("添加视频源失败");
                    return;
                }
                if (!m_pVideoCap.VideoCapStart())
                {
                    MessageBox.Show("开始录像失败");
                    return;
                }
                else
                {
                    MessageBox.Show("开始录像");
                }
            }
        }

        private void stopRecord_Click(object sender, RoutedEventArgs e)
        {
            if (null != m_pVideo)
            {
                if (null != m_pVideoCap)
                {
                    m_pVideoCap.VideoCapStop();
                    m_pVideoCap.Destroy();
                    m_pVideoCap = null;
                    MessageBox.Show("录像已停止，保存在D:/eloamVideo.mp4");
                }
            }
        }

        private void button_StartIdCardRead_Click(object sender, RoutedEventArgs e)
        {
            global.DiscernIdCard();
        }

        private void button_StopReadIDCard_Click(object sender, RoutedEventArgs e)
        {
            global.StopIdCardDiscern();
        }

        private void chkAll_Click(object sender, RoutedEventArgs e)
        {
            for (int i = 0; i < eloamThumbnail.GetCount(); i++)
            {
                eloamThumbnail.SetCheck(i, (bool)chkAll.IsChecked);
            }
        }

        /// <summary>
        /// 读文件到byte[]
        /// </summary>
        /// <param name="fileName">硬盘文件路径</param>
        /// <returns></returns>
        public byte[] ReadFileToByte(string fileName)
        {
            FileStream pFileStream = null;
            byte[] pReadByte = new byte[0];
            try
            {
                pFileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
                BinaryReader r = new BinaryReader(pFileStream);
                r.BaseStream.Seek(0, SeekOrigin.Begin);    //将文件指针设置到文件开
                pReadByte = r.ReadBytes((int)r.BaseStream.Length);
                return pReadByte;
            }
            catch
            {
                return pReadByte;
            }
            finally
            {
                if (pFileStream != null)
                    pFileStream.Close();
            }
        }
        private void test_Click(object sender, RoutedEventArgs e)
        {
            //var byteData = ReadFileToByte(@"D:\投标助手图片\01.png");
            //var strMsg = client.UploadFileToFtp(ftpUrl, userName, passWord, byteData, "aaaaa.png", "12345678", userid, "身份证", ftpDirctory);

            var ftpUrl = "ftp://ftpuser:ftpuser@10.101.203.100:21";
            var flag = client.DownloadFileForDirectory(ftpUrl, userName, passWord, "2017102000008", "D:\\2017102000008\\", "");
        }
    }


    public class Info
    {
        public string Id { get; set; }
        public string Name { get; set; }

    }
    public class FamilyInfo
    {
        public string Iid { get; set; }

        public string Name { get; set; }

        public string CardId { get; set; }

        public string Status { get; set; }

        public string Fwjzmj { get; set; }
    }
}
